package RateService

import (
	RateModel "blog/app/models/rate_model"
	"blog/config"
	"blog/service"
	"blog/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
	"time"
)

// 处理汇率配置和初始化信息相关

// GetExcelSaveDb 读取Excel数据写入MySQL https://www.iban.hk/currency-codes
func GetExcelSaveDb(c *gin.Context) {
	// 打开Excel文件
	excelFileName := "static/code.xlsx"
	xlFile, err := xlsx.OpenFile(excelFileName)
	if err != nil {
		fmt.Printf("Error opening Excel file: %s\n", err)
		return
	}

	// 遍历每个工作表
	for _, sheet := range xlFile.Sheets {
		fmt.Printf("Sheet Name: %s\n", sheet.Name)
		// 遍历每一行
		for i, row := range sheet.Rows {
			fmt.Printf("行数Row %d\n", i)
			// 遍历每个单元格
			item := RateModel.CurrencyName{
				CreatedTime: time.Now(),
				UpdatedTime: time.Now(),
				CreatedBy:   "system",
				UpdatedBy:   "system",
			}
			for index, cell := range row.Cells {
				text := cell.String()
				fmt.Printf("%d : %s\t", index, text)
				switch index {
				case 0:
					item.CurrencyOwer = text
					break
				case 1:
					item.CurrencyName = text
				case 2:
					item.CurrencyCode = text
					break
				default:
					break
				}
			}
			fmt.Println("item", item)
			if i != 0 {
				// 把数据写入db
				err := utils.MySqlDB.Model(&RateModel.CurrencyName{}).Save(&item)
				if err.Error != nil {
					fmt.Printf("Error creating item: %v\n", err)
				}
			}
		}
	}
	service.CommonCJsonReply(c, config.SUCCESS, config.SUCCESS)
}
